<template>
  <div class="form-container">
    <div class="title-wrap">
      <a-row>
        <a-col :span="18" :offset="10"> <span class="title">登录</span> </a-col>
      </a-row>
    </div>
    <CustomForm
      ref="LoginForm"
      :formRootInstance="formRootInstance"
      :formRules="formRules"
      :initModel="initModel"
      :tempModel="tempModel"
      :submitButtonOptions="submitButtonOptions"
      :curCaptchaPath="curCaptchaPath"
      @refreshAuthCode="getCaptchaPath"
      @submit="handleSubmitForm"
    >
      <template v-slot:other>
        <a-row class="slot-class">
          <a-col :span="12" :offset="3">
            <span class="a-tag-init" @click="cbOperation('register')"
              >还没有账户？点击注册</span
            >
          </a-col>
          <a-col :span="7" :offset="2">
            <span class="a-tag-init" @click="cbOperation('forget')"
              >忘记密码</span
            >
          </a-col>
        </a-row>
      </template>
      <template v-slot:footer>
        <a-row>
          <a-col :span="6" :offset="11">
            <a class="a-tag-init" @click="reset">重置</a>
          </a-col>
        </a-row>
      </template>
    </CustomForm>
    <Loading :loading="loading" />
    <!-- 弹窗 -->
    <custom-modal :title="modalTitle" :modalVisible="modalVisible">
      <ModalStatus
        btnTitle="确定"
        :headTitle="headTitle"
        :btnList="btnList"
        @cancel="() => (modalVisible = false)"
        @exitLogin="emailLogin"
      />
    </custom-modal>
  </div>
</template>

<script>
// import qs from 'qs'
import { mapGetters, mapMutations } from 'vuex'
import encrypt from '@/utils/cryptoJs.js'
import CustomForm from '@/components/CustomForm/index'
import CustomModal from '@/components/CustomModal/index'
import Loading from '@/components/Loading/index'
import ModalStatus from '@/components/Modals/ModalStatus'
import mixinConfigSetting from '@/mixins/mixinConfigSetting'
import mixinLogin from '../mixins/index'
// import { checkToken, emailToken } from '@/api/user'
import { MODAL_FOOTER_CONFIG } from '../config/modal'
import { captchaImage } from '@/api/user'
// import { captchaImage, Login } from '@/api/user'
// import { setStorage } from '@/utils/index'

export default {
  mixins: [mixinConfigSetting, mixinLogin],
  components: {
    CustomForm,
    CustomModal,
    ModalStatus,
    Loading
  },
  props: {
    formConfig: Object // 表单配置对象(在mixinConfigSetting 中统一处理了)
  },
  data() {
    return {
      modalVisible: false,
      modalTitle: '', // 弹窗标题
      headTitle: '', // 弹窗内部标题
      btnList: MODAL_FOOTER_CONFIG.btnList,
      uuid: ''
    }
  },
  mounted() {
    // 验证码
    this.getCaptchaImage()
  },
  computed: {
    ...mapGetters('user', [
      'role',
      'account',
      'visitor',
      'token'
    ])
  },
  methods: {
    ...mapMutations('user', [
      'SET_ACCOUNT',
      'SET_ROLE',
      'SET_TOKEN'
    ]),
    reset() {  //调用组件的清空方法
      this.$refs.LoginForm.resetForm()
    },
    getCaptchaImage() {
      captchaImage().then((res) => {
        if (res.code === 200) {
          this.curCaptchaPath = `data:image/gif;base64,${res.img}`
          this.uuid = res.uuid
        }
      })
    },
    getCaptchaPath() {
      this.getCaptchaImage()
    },
    handleSubmitForm(formValue) {
      this.callWithHandlerError(async () => {
        const { form } = formValue
        this.normalizeLoginForm(form) // 格式化表单
        this.$store.dispatch('user/LoginForm', form).then((res) => {
          if (res.code === 200) {
            this.$message.success('登录成功!')
            this.emailLogin() // 执行登录逻辑
          } else {
            this.getCaptchaPath() // 重新获取验证码
            this.$message.warning(res.msg)
          }
        })
      })
    },
    normalizeLoginForm(form) { // 标准化参数
      const { password, email } = form
      this.loginForm = {
        client_id: window.APP_CONFIG.loginData.client_id,
        client_secret: window.APP_CONFIG.loginData.client_secret,
        grant_type: 'password',
        email,
        password: encrypt(password, this.uuid),
        code: form.code,
        uuid: this.uuid,
        crowd_out: false,
        scope: 'select'
      }
      form.uuid = this.uuid
      // this.checkToken(email)
    },
    // async checkToken(email) {
    //   const accountStatue = await checkToken(qs.stringify({ email }))
    //   const { data, status } = accountStatue
    //   if (data && status === 1) { // 已经登录
    //     // 当前账号已经登录
    //     this.modalTitle = '当前账号已经登录'
    //     this.headTitle = '此账号已在其他设备登录，是否在其他设备退出，并在此设备登录？'
    //     this.modalVisible = true
    //   }
    // },
    async emailLogin() {
      // this.modalVisible = false // 如果显示状态要隐藏
      // const res = await emailToken(this.loginForm)
      // const { status, message } = res
      // if (status === 0) {
      //   throw Error(message)
      // }
      // const result = res.data.body
      // if (result && result.loginErrorMsg) { // 登录异常
      //   throw Error(result.loginErrorMsg)
      // }
      // if (result) {
      //   this.$store.dispatch('user/loginIn', result) // 设置用户信息并且请求用户详情
      //   await this.$store.dispatch('user/getUserInfo')
      //   this.$apiStatusHandler(0, '登录成功')
      let path = '/platformPortal'
      this.$router.push({ path: path })
      // let redirect = this.$route.query.redirect || path
      // const key = this.$route.query.key || ''
      // if (redirect !== '/' || (redirect && redirect.indexOf('/login') === -1)) {
      //   path = redirect
      // }
      // this.$router.push({
      //   path,
      //   query: {
      //     key
      //   }
      // })
    }
  }
}
</script>